package com.atguigu.gmall.mq.receiver;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(queues = "queue1")//监听器
public class ConsumerMessage {


    //接收
    //@RabbitHandler
    @RabbitListener(queues = "queue1")
    public void message(String message){
        System.out.println("接收1："+message);
    }

    //代码绑定接收
    //bindings = {}，{}，{}       durable：持久化
    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(name = "queue2",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "exchange2"),
            key = {"routingKey2"}
    )})
    public void message2(String msg, Message message, Channel channel){
        System.out.println("queue2接收："+msg);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            //第一次进入
            System.out.println("第一次进入，再处理");
            if (!message.getMessageProperties().isRedelivered()){
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }else {
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
